package cn.alex.sso.project.controller;

import cn.alex.sso.framework.annotations.OperatLog;
import cn.alex.sso.framework.constant.ModuleConstant;
import cn.alex.sso.framework.core.PageHelper;
import cn.alex.sso.framework.core.Result;
import cn.alex.sso.project.entity.SysUser;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.sso.template.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 在线用户
 *
 * @author Alex
 * @date 2024/10/17 上午10:01
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user/online")
public class SysUserOnlineController {

    /**
     * 获取分页列表
     */
    @GetMapping("/getPage")
    public Result getPage(@RequestParam(defaultValue = "") String userId) {
        Map<String, Object> result = new HashMap<>();
        long count = StpUtil.searchSessionId(userId, -1, -1, true).size();
        result.put("total", count);

        List<String> sessionIdList = StpUtil.searchSessionId(userId, PageHelper.getPageStart(), PageHelper.getPageEnd(), true);

        List<Map<String, Object>> records = sessionIdList.stream()
                .map(StpUtil::getSessionBySessionId)
                .map(session -> {
                    Map<String, Object> info = new HashMap<>();
                    info.put("sessionId", session.getId());
                    info.put("tokenSignList", session.getTokenSignList());
                    info.put("createdTime", session.getCreateTime());
                    info.put("timeout", session.getTimeout());

                    SysUser user = session.getModel("user", SysUser.class);
                    if (user != null) {
                        info.put("userId", user.getId());
                        info.put("username", user.getUsername());
                        info.put("nickName", user.getNickName());
                        info.put("avatar", user.getAvatar());
                    }
                    return info;
                }).collect(Collectors.toList());
        result.put("records", records);
        return Result.ok(result);
    }

    /**
     * 强制下线
     */
    @PostMapping("/logout/{sessionId}")
    @OperatLog(module = ModuleConstant.ONLINE_USER, action = "强制下线")
    public Result logout(@PathVariable String sessionId) {
        SaSession session = StpUtil.getSessionBySessionId(sessionId);
        Object loginId = session.getLoginId();
        SaSsoUtil.ssoLogout(loginId);
        return Result.ok();
    }
}
